package com.example.ws.handler.erole;

import static io.javalin.apibuilder.ApiBuilder.get;
import static io.javalin.apibuilder.ApiBuilder.post;

import java.util.HashMap;
import java.util.Map;

import com.example.ws.handler.elog.ELogHandler;
import com.example.ws.util.RespUtil;

import io.javalin.apibuilder.EndpointGroup;
import io.javalin.http.Context;

public class ERoleHandler implements EndpointGroup {

    public static Map<String, String> eroleJsonDataMap = new HashMap<>();
    public static boolean changed = false;

    @Override
	public void addEndpoints() {
        
        // 存入json
        post("json", ERoleHandler::eroleJson);
        // 获取json
        get("json", ERoleHandler::getEroleJson);
        // 获取debug json
        get("debug_json", ERoleHandler::getDebugEroleJson);
        
    }

    public static void eroleJson(Context ctx) {
        ERoleEntity entity = ctx.bodyAsClass(ERoleEntity.class);
        eroleJsonDataMap.put(entity.getKey(), entity.getValue());
        System.out.println("收到请求前准备处理...changed: " + changed);
        RespUtil.success(ctx, "ok");
    }

    // 获取json 
    // 请求参数：key
    public static void getEroleJson(Context ctx) {
        ERoleWatchData data = new ERoleWatchData();
        String key = ctx.queryParam("key");
        if (key == null || key.isEmpty() || !eroleJsonDataMap.containsKey(key)  ) {
            RespUtil.error(ctx, "key not found, key: " + key);
            return;
        }
        data.setJData(eroleJsonDataMap.get(key));
        data.setKey(key);
        RespUtil.success(ctx, data);
    }

    public static void getDebugEroleJson(Context ctx) {
        String key = ctx.queryParam("key");
        RespUtil.success(ctx, new ERoleWatchData(changed, eroleJsonDataMap.get(key), key));
    }

    public static synchronized void changed(boolean changed) {
        ERoleHandler.changed = changed;
    }
}
